package net.lab1024.sa.admin.module.system.login.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.servlet.JakartaServletUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import net.lab1024.sa.admin.constant.AdminSwaggerTagConst;
import net.lab1024.sa.admin.module.system.login.domain.LoginForm;
import net.lab1024.sa.admin.module.system.login.domain.LoginResultVO;
import net.lab1024.sa.admin.module.system.login.service.LoginService;
import net.lab1024.sa.admin.util.AdminRequestUtil;
import net.lab1024.sa.base.common.annoation.NoNeedLogin;
import net.lab1024.sa.base.common.constant.RequestHeaderConst;
import net.lab1024.sa.base.common.domain.ResponseDTO;
import net.lab1024.sa.base.common.util.SmartRequestUtil;
import net.lab1024.sa.base.module.support.captcha.domain.CaptchaVO;
import net.lab1024.sa.base.module.support.securityprotect.service.Level3ProtectConfigService;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 员工登录
 *
 * @Author 1024创新实验室-主任:卓大
 * @Date 2021-12-15 21:05:46
 * @Wechat zhuoda1024
 * @Email lab1024@163.com
 * @Copyright <a href="https://1024lab.net">1024创新实验室</a>
 */
@RestController
@Tag(name = AdminSwaggerTagConst.System.SYSTEM_LOGIN)
public class LoginController {

    @Resource
    private LoginService loginService;

    @Resource
    private Level3ProtectConfigService level3ProtectConfigService;

    @NoNeedLogin
    @PostMapping("/login")
    @Operation(summary = "登录 @author 卓大")
    public ResponseDTO<LoginResultVO> login(@Valid @RequestBody LoginForm loginForm, HttpServletRequest request) {
        String ip = JakartaServletUtil.getClientIP(request);
        String userAgent = JakartaServletUtil.getHeaderIgnoreCase(request, RequestHeaderConst.USER_AGENT);
        return loginService.login(loginForm, ip, userAgent);
    }

    @GetMapping("/login/getLoginInfo")
    @Operation(summary = "获取登录结果信息  @author 卓大")
    public ResponseDTO<LoginResultVO> getLoginInfo() {
        String tokenValue = StpUtil.getTokenValue();
        LoginResultVO loginResult = loginService.getLoginResult(AdminRequestUtil.getRequestUser(), tokenValue);
        loginResult.setToken(tokenValue);
        return ResponseDTO.ok(loginResult);
    }

    @Operation(summary = "退出登录  @author 卓大")
    @GetMapping("/login/logout")
    public ResponseDTO<String> logout() {
        return loginService.logout(SmartRequestUtil.getRequestUser());
    }

    @Operation(summary = "获取验证码  @author 卓大")
    @GetMapping("/login/getCaptcha")
    @NoNeedLogin
    public ResponseDTO<CaptchaVO> getCaptcha() {
        return loginService.getCaptcha();
    }

    @NoNeedLogin
    @GetMapping("/login/sendEmailCode/{loginName}")
    @Operation(summary = "获取邮箱登录验证码 @author 卓大")
    public ResponseDTO<String> sendEmailCode(@PathVariable String loginName) {
        return loginService.sendEmailCode(loginName);
    }


    @NoNeedLogin
    @GetMapping("/login/getTwoFactorLoginFlag")
    @Operation(summary = "获取双因子登录标识 @author 卓大")
    public ResponseDTO<Boolean> getTwoFactorLoginFlag() {
        // 双因子登录
        boolean twoFactorLoginEnabled = level3ProtectConfigService.isTwoFactorLoginEnabled();
        return ResponseDTO.ok(twoFactorLoginEnabled);
    }

//    /**
//     * 获取跳转URL
//     *
//     * @param source 登录来源
//     * @return 结果
//     */
//    @GetMapping("/binding/{source}")
//    public ResponseDTO<String> authBinding(@PathVariable("source") String source,
//                                 @RequestParam String tenantId, @RequestParam String domain) {
//        SocialLoginConfigProperties obj = socialProperties.getType().get(source);
//        if (ObjectUtil.isNull(obj)) {
//            return ResponseDTO.fail(source + "平台账号暂不支持");
//        }
//        AuthRequest authRequest = SocialUtils.getAuthRequest(source, socialProperties);
//        Map<String, String> map = new HashMap<>();
//        map.put("tenantId", tenantId);
//        map.put("domain", domain);
//        map.put("state", AuthStateUtils.createState());
//        String authorizeUrl = authRequest.authorize(Base64.encode(JsonUtils.toJsonString(map), StandardCharsets.UTF_8));
//        return ResponseDTO.ok("操作成功", authorizeUrl);
//    }
//
//    /**
//     * 前端回调绑定授权(需要token)
//     *
//     * @param loginBody 请求体
//     * @return 结果
//     */
//    @PostMapping("/social/callback")
//    public ResponseDTO<Void> socialCallback(@RequestBody SocialLoginBody loginBody) {
//        // 校验token
//        StpUtil.checkLogin();
//        // 获取第三方登录信息
//        AuthResponse<AuthUser> response = SocialUtils.loginAuth(
//                loginBody.getSource(), loginBody.getSocialCode(),
//                loginBody.getSocialState(), socialProperties);
//        AuthUser authUserData = response.getData();
//        // 判断授权响应是否成功
//        if (!response.ok()) {
//            return R.fail(response.getMsg());
//        }
//        loginService.socialRegister(authUserData);
//        return ResponseDTO.ok();
//    }
//
//
//    /**
//     * 取消授权(需要token)
//     *
//     * @param socialId socialId
//     */
//    @DeleteMapping(value = "/unlock/{socialId}")
//    public ResponseDTO<Void> unlockSocial(@PathVariable Long socialId) {
//        // 校验token
//        StpUtil.checkLogin();
//        Boolean rows = socialUserService.deleteWithValidById(socialId);
//        return rows ? ResponseDTO.ok() : ResponseDTO.fail("取消授权失败");
//    }

}
